package cn.cxq.learning.sparse_array;

public class SparseArray {

    public static int[][] convertIntoSparseArray(int[][] arr){

        int sum = 0;//数组非零值个数

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] != 0)
                {
                    sum ++;
                }
            }
        }

        //初始化稀疏数组
        int[][] sparseArr = new int[sum+1][3];

        sparseArr[0][0] = arr.length;
        sparseArr[0][1] = arr[0].length;
        sparseArr[0][2] = sum;

        int index = 0;//系数数组当前下标

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] != 0)
                {
                    index ++;
                    sparseArr[index][0]=i;
                    sparseArr[index][1]=j;
                    sparseArr[index][2]=arr[i][j];
                }
            }
        }
        return sparseArr;
    }

    public static int[][] convertIntoArray(int[][] sparseArr){
        int[][] arr = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
                arr[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        return arr;
    }
}
